/// @author  Alberto Franco
/// @file    sender.go
/// @date    05-05-2011
/// @brief   Contains the data structure used by the Sender to send data
package netsim

import (
    "fmt"
)

/// Sender structure receive data from the application layer and sends it to
/// the network. It is based on acks.
type Sender struct {
    //--- VARS -----------------------------------------------------------------
    name string ///< Name of the sender
    //--- CHANS ----------------------------------------------------------------
    input       *chan int32 ///< Receive from the application layer pkst
    errorChan   *chan int32 ///< Error channel, if the medium is congested 
    ackChan     *chan int32 ///< Receive back acks
    pktChan     chan int32 ///< Send packets over this 
}

/// Create a new sender with the given name
func CreateSender(name string) *Sender{
    var sender *Sender = new (Sender)
    sender.pktChan = make (chan int32)
    return sender
}

/// Sender is described in CCS as follows:
/// Sender     = in(x).Sending(x)
/// Sending(x) = 'send(x).Waiting(x)
/// Waiting(x) = ack.Sender + error.Sending(x)
func (self *Sender) SendData() {
    var packet int32
    var pktSent bool
    for {
        // Receive a packet
        packet = <- (*self.input)
        pktSent = false
        // Try to send it over the net
        for (!pktSent) {
            fmt.Println(self.name + " try to send a packet...")
            self.pktChan <- packet
            /// Now made a choise depending if returns an ack or an error
            select {
                case <- (*self.ackChan):
                    fmt.Println("Packet sent!")
                    pktSent = true
                case <- (*self.errorChan):
                    fmt.Println("Error in pkt")
            }
        }
    }
}


